package keepaliveddeploylogic

import (
	"context"
	"os"

	"yunzhan/rpc-server/internal/svc"
	agent "yunzhan/rpc-server/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetKeepalivedConfigLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetKeepalivedConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetKeepalivedConfigLogic {
	return &GetKeepalivedConfigLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetKeepalivedConfigLogic) GetKeepalivedConfig(in *agent.GetKeepalivedConfRequest) (*agent.BaseKeepalivedConfResponse, error) {
	filePath := "/usr/local/keepalived-2.3.1/etc/keepalived.conf"

	// 检查文件是否存在
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return &agent.BaseKeepalivedConfResponse{
			Code:    500,
			Message: "keepalived.conf配置文件不存在",
		}, nil
	}

	// 读取文件内容
	content, err := os.ReadFile(filePath)
	if err != nil {
		logx.Errorf("读取keepalived.conf配置文件失败: %v", err)
		return &agent.BaseKeepalivedConfResponse{
			Code:    500,
			Message: "读取keepalived.conf配置文件失败",
		}, err
	}

	// 返回文件内容
	return &agent.BaseKeepalivedConfResponse{
		Code:    200,
		Message: "Success",
		Content: string(content),
	}, nil
}
